import { dialog } from 'electron'
import ffmpeg from 'fluent-ffmpeg'
import path from 'path'
import fs from 'fs'

export default {
  name: 'file',

  // 选择文件
  async selectFile(app, filters = {}) {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'], // 也可以用 openDirectory 选择文件夹
      filters: [filters, { name: 'All Files', extensions: ['*'] }].filter(
        (item) => Object.keys(item).length
      )
    })

    if (!result.canceled) {
      return result.filePaths[0]
    }
  },
  // 新增：选择Excel文件
  async selectExcelFile(app, filters = {}) {
    const result = await dialog.showOpenDialog({
      title: '选择Excel文件',
      filters: [filters, { name: 'Excel Files', extensions: ['xlsx', 'xls'] }],
      properties: ['openFile']
    })

    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0]
    }
    return null
  },
  // 新增：选择多个文件（通用方法）
  async selectMultipleFiles(app, options = {}) {
    const defaultOptions = {
      title: '选择多个文件',
      filters: [{ name: 'All Files', extensions: ['*'] }],
      properties: ['openFile', 'multiSelections']
    }

    // 合并选项
    const dialogOptions = {
      ...defaultOptions,
      ...options,
      filters: options.filters || defaultOptions.filters
    }

    const result = await dialog.showOpenDialog(dialogOptions)

    if (!result.canceled) {
      return result.filePaths
    }
    return []
  },
  async selectAudioFile(app, filters = {}) {
    const result = await dialog.showOpenDialog({
      title: '选择多个音频文件',
      filters: [filters, { name: 'Audio Files', extensions: ['mp3', 'wav', 'flac', 'm4a'] }],
      properties: ['openFile', 'multiSelections']
    })

    return result.filePaths
  },
  // 新增方法：选择文件夹/目录
  async selectFileDirectory() {
    try {
      return await dialog.showOpenDialog({
        title: '选择保存位置',
        properties: ['openDirectory']
      })
    } catch (error) {
      console.error('选择目录失败:', error)
      return null
    }
  },
  // 新增批量保存文件方法
  async saveMultipleFiles() {
    try {
      // 选择保存目录而非单个文件
      return await dialog.showOpenDialog({
        title: '选择保存位置',
        properties: ['openDirectory']
      })
    } catch (error) {
      console.error('选择保存位置失败:', error)
      return null
    }
  },
  async saveFile(app, defaultPath = '') {
    const result = await dialog.showSaveDialog({
      defaultPath
    })
    if (!result.canceled) {
      return result.filePath
    }
  },
  async getVideoInfo(app, videoPath) {
    return new Promise((resolve) => {
      ffmpeg(videoPath).ffprobe((err, data) => {
        if (err) {
          resolve({ isOK: false, msg: err.toString() })
        } else if (data?.streams?.length > 0) {
          resolve(
            Object.assign(
              { isOK: true, name: path.basename(videoPath) },
              data.format,
              data.streams.find((item) => item.codec_type === 'video')
            )
          )

        } else {
          resolve({ isOK: false, msg: 'No streams found' })
        }
      })
    })
  },
  // 新增：读取文件Buffer
  async readBuffer(app, filePath) {
    try {
      return fs.promises.readFile(filePath)
    } catch (error) {
      console.error('读取文件失败:', error)
      throw error
    }
  },

  // 新增：获取文件信息
  async getFileInfo(app, filePath) {
    try {
      const stats = await fs.promises.stat(filePath)
      const extension = path.extname(filePath).toLowerCase().substring(1)

      return {
        isOK: true,
        name: path.basename(filePath),
        size: stats.size,
        extension,
        lastModified: stats.mtime,
        created: stats.birthtime,
        type: this.getFileType(extension)
      }
    } catch (error) {
      return { isOK: false, msg: error.toString() }
    }
  },
  async getAudioInfo(app, audioPath) {
    return new Promise((resolve) => {
      ffmpeg(audioPath).ffprobe((err, data) => {
        if (err) {
          resolve({ isOK: false, msg: err.toString() })
        } else if (data?.streams?.length > 0) {
          resolve(
            Object.assign(
              { isOK: true, name: path.basename(audioPath) },
              data.format,
              data.streams.find((item) => item.codec_type === 'audio')
            )
          )
        } else {
          resolve({ isOK: false, msg: 'No streams found' })
        }
      })
    })
  },
  // 新增：获取Excel文件信息
  async getExcelInfo(app, excelPath) {
    try {
      const stats = await fs.promises.stat(excelPath)
      return {
        isOK: true,
        name: path.basename(excelPath),
        size: stats.size,
        extension: path.extname(excelPath).toLowerCase().substring(1),
        lastModified: stats.mtime
      }
    } catch (error) {
      return { isOK: false, msg: error.toString() }
    }
  },
  // 新增：辅助方法 - 根据扩展名获取文件类型
  getFileType(extension) {
    const mimeTypes = {
      // 视频类型
      mp4: 'video/mp4',
      mov: 'video/quicktime',
      avi: 'video/x-msvideo',
      mkv: 'video/x-matroska',

      // 音频类型
      mp3: 'audio/mpeg',
      wav: 'audio/wav',
      flac: 'audio/flac',
      m4a: 'audio/m4a',

      // Excel类型
      xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      xls: 'application/vnd.ms-excel',

      // 文本类型
      txt: 'text/plain',
      csv: 'text/csv',

      // 默认类型
      default: 'application/octet-stream'
    }

    return mimeTypes[extension] || mimeTypes.default
  },
  async saveCaptionFile(app, captionPath, captionContent){
    try {
      fs.writeFileSync(captionPath, captionContent, 'utf-8')

      return {
        success: true,
        message: '字幕保存成功'
      }
    } catch (err) {
      console.error('保存字幕失败:', err)
      return {
        success: false,
        message: '字幕保存失败'
      }
    }
  }
}
